//
//  MusicViewController.m
//  ToWhere
//
//  Created by dllo on 15/11/21.
//  Copyright © 2015年 www.TE.com. All rights reserved.
//

#import "MusicViewController.h"
#import "DataAnalysis.h"
#import "MusicModel.h"
#import "MusicCollectionViewCell.h"
#import "SDCycleScrollView.h"
#import "MusicLBTDetailViewController.h"
#import "MusicLBTDetailWebViewController.h"
#import "MusicAllModel.h"
#import <MJRefresh.h>
#import "MusciDetailViewController.h"
#import "MusicPlayViewController.h"
#import "SaveTools.h"

@interface MusicViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, SDCycleScrollViewDelegate>

@property(nonatomic, retain) UIView *titleView;

@property(nonatomic, retain) UICollectionView *collectionView;

@property(nonatomic, retain) NSMutableArray *LBTArray;

@property(nonatomic, retain) UIView *LBTBackView;

@property(nonatomic, assign) NSInteger page;

@property(nonatomic, retain) NSMutableArray *AllArray;

@property(nonatomic, retain) MJRefreshAutoGifFooter *footer;

@property (nonatomic, retain) UIAlertController *al;

@end

@implementation MusicViewController

- (void)dealloc
{
    [_collectionView release];
    [_LBTArray release];
    [_LBTBackView release];
    [_titleView release];
    [_footer release];
    [_al release];
    [_AllArray release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化
    [self initData];
    
    //创建标题
    [self createTitle];
    
    //轮播图解析数据
    [self loadLBTData];
    
    //全部数据解析
    [self loadData];
    
    //创建CollectionView
    [self createCollectionView];
    
    UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Music_LBT.jpg"]];
    image.frame = CGRectMake(5 * kWidth, -205 * kHeight, self.view.frame.size.width - 10 * kWidth, 200 * kHeight);
    [self.collectionView addSubview:image];
    [image release];
    
    //下拉加载
    self.footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.collectionView.footer = self.footer;
    
    

}

#pragma mark 初始化
-(void)initData
{
    self.LBTArray = [NSMutableArray array];
    self.page = 1;
    self.AllArray = [NSMutableArray array];
}

#pragma mark 创建标题
-(void)createTitle
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,kHeight * 64)];
    self.titleView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.titleView];
    [self.titleView release];
    [_titleView release];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 100 * kWidth, self.titleView.frame.size.height / 2 - 10 * kHeight, kWidth * 200, kHeight * 30)];
    titleLabel.text = @"音旅";
    titleLabel.font = [UIFont systemFontOfSize:17 * kWidth];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.titleView addSubview:titleLabel];
    [titleLabel release];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundImage:[UIImage imageNamed:@"Music"] forState:UIControlStateNormal];
    btn.frame = CGRectMake(340 * kWidth, self.titleView.frame.size.height / 2 - 7 * kHeight, 30 * kWidth, 30 * kWidth);
    [self.titleView addSubview:btn];
    [btn addTarget:self action:@selector(playViewAction:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)playViewAction:(UIButton *)btn
{
    NSString *music = [SaveTools readFromFileName:@"music" andFilePath:NSLibraryDirectory];
    if (music == nil) {
        self.al = [UIAlertController alertControllerWithTitle:nil message:@"还没有你的播放印记哦!" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:self.al animated:YES completion:nil];
        [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(remove) userInfo:nil repeats:YES];
    }
    else
    {
        MusicPlayViewController *player = [MusicPlayViewController shareMusicPlayViewController];
        [self setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:player animated:YES];
        [self setHidesBottomBarWhenPushed:NO];
    }
}
- (void)remove{
    [self.al dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark 解析数据
-(void)loadLBTData
{
    //轮播图数据解析
    [DataAnalysis dataAnalysisGETWithUrlString:@"http://api.dongting.com/frontpage/frontpage?v=v8.2.0.2015091720" parameters:nil showHuD:YES hiddenView:nil successfulBlock:^(id responseObject) {
        for (NSDictionary *dic in [[[responseObject objectForKey:@"data"] firstObject] objectForKey:@"data"]) {
            if ([[[dic objectForKey:@"action"] objectForKey:@"type"] integerValue] == 1) {
                MusicModel *music = [MusicModel musicWithDictionary:dic];
                [self.LBTArray addObject:music];
            }
        }
        
        [self.LBTBackView removeFromSuperview];
        if (self.LBTArray.count >= 1) {
            //创建轮播图
            [self createLBT];
        }       

    } failureBlock:^(NSError *error) {
        NSLog(@"error: %@", error);
    }];
}

-(void)loadData
{
    //全部分类数据解析
    [DataAnalysis dataAnalysisGETWithUrlString:[NSString stringWithFormat:@"http://echosystem.kibey.com/channel/get?with_sound=0&order=hot&page=%ld", self.page] parameters:nil showHuD:YES hiddenView:nil successfulBlock:^(id responseObject) {
        
        for (NSDictionary *dic in [[responseObject objectForKey:@"result"] objectForKey:@"data"]) {
            MusicAllModel *allModel = [MusicAllModel musicAllWithDictionary:dic];
            [self.AllArray addObject:allModel];
        }
        [self.collectionView reloadData];
        [self.collectionView.footer endRefreshing];
    } failureBlock:^(NSError *error) {
        NSLog(@"error : %@", error);
    }];
}

-(void)loadMoreData
{
    _page += 1;
    [self loadData];
}

#pragma mark 创建collectionView
-(void)createCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64 * kHeight, self.view.frame.size.width, self.view.frame.size.height - 113 * kHeight) collectionViewLayout:flowLayout];
    self.collectionView.contentInset = UIEdgeInsetsMake(210 * kHeight, 0, 0, 0);
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[MusicCollectionViewCell class] forCellWithReuseIdentifier:@"MusicCollectionViewCell"];
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];

    
    //注册头尾视图
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerView"];

    [_collectionView release];
    [flowLayout release];
    
}

//返回行数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.AllArray.count;
}

//返回分区数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//左右间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5 * kWidth;
}

//行间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 5 * kHeight;
}

//items大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(self.view.frame.size.width / 2 - 9 * kWidth, 120 * kHeight);
}

//内间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5 * kHeight, 5 * kWidth, 5 * kWidth, 5 * kHeight);
}

//头尾视图
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = @[@"经典推荐"];
    if (kind == UICollectionElementKindSectionHeader) {
        
        UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        reusableView.backgroundColor = [UIColor colorWithRed:0.953 green:0.952 blue:0.973 alpha:1.000];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20 * kWidth, 10 * kHeight, 100 * kWidth, 30 * kHeight)];
        titleLabel.font = [UIFont systemFontOfSize:16];
        titleLabel.backgroundColor = [UIColor colorWithRed:0.953 green:0.952 blue:0.973 alpha:1.000];
        titleLabel.text = array[indexPath.section];
        [reusableView addSubview:titleLabel];
        [titleLabel release];
        
        UILabel *label = [[UILabel alloc] init];
        label.frame = CGRectMake(10 * kWidth, 17 * kHeight, 5 *kWidth, 15 * kHeight);
        label.backgroundColor = [UIColor colorWithRed:0.400 green:1.000 blue:0.800 alpha:1.000];
        [reusableView addSubview:label];
        [label release];
        
         return reusableView;
    }
    else
    {
        UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerView" forIndexPath:indexPath];
        reusableView.backgroundColor = [UIColor colorWithWhite:0.927 alpha:1.000];
        return reusableView;
    }
}

//返回头视图高
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(self.view.frame.size.width, 40 * kHeight);
}

//尾视图高
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(self.view.frame.size.width, 1 * kHeight);
}

//重用池
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MusicCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MusicCollectionViewCell" forIndexPath:indexPath];
    cell.musicAllModel = self.AllArray[indexPath.row];
    return cell;
}

//点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MusciDetailViewController *detail = [[MusciDetailViewController alloc]init];
    detail.allModel = self.AllArray[indexPath.row];
    [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:detail animated:YES];
    [self setHidesBottomBarWhenPushed:NO];
}

#pragma mark 创建轮播图
-(void)createLBT
{
    self.LBTBackView = [[UIView alloc]initWithFrame:CGRectMake(0, -210 * kHeight, self.view.frame.size.width, 210 * kHeight)];
    self.LBTBackView.backgroundColor = [UIColor colorWithRed:0.953 green:0.952 blue:0.973 alpha:1.000];
    [self.collectionView addSubview:self.LBTBackView];
    [_LBTBackView release];
    
    NSMutableArray *array = [NSMutableArray array];
    for (MusicModel *music in self.LBTArray) {
        [array addObject:music.picUrl];
    }
    SDCycleScrollView *sdcycle = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(5 * kWidth, 5 * kHeight, self.view.frame.size.width - 10 * kWidth, 200 * kHeight) imageURLStringsGroup:array];
    sdcycle.delegate = self;
    [self.LBTBackView addSubview:sdcycle];
    
}

#pragma mark 轮播图的代理方法
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    if ([[[self.LBTArray[index] Action] objectForKey:@"type"] integerValue] == 1) {
        MusicLBTDetailWebViewController *LBTWebView = [[MusicLBTDetailWebViewController alloc]init];
        LBTWebView.webUrl = [[self.LBTArray[index] Action] objectForKey:@"value"];
        LBTWebView.name = [self.LBTArray[index] name];
        [self setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:LBTWebView animated:YES];
        [self setHidesBottomBarWhenPushed:NO];
    }
    else
    {
        MusicLBTDetailViewController *detail = [[MusicLBTDetailViewController alloc]init];
        detail.value = [[self.LBTArray[index] Action] objectForKey:@"value"];
        detail.name = [self.LBTArray[index] name];
        detail.listenCount = [self.LBTArray[index] listenCount];
        [self setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:detail animated:YES];
        [self setHidesBottomBarWhenPushed:NO];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
